package com.atguigu.day11;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.functions.ScalarFunction;
import org.apache.flink.types.Row;

import static org.apache.flink.table.api.Expressions.$;
import static org.apache.flink.table.api.Expressions.call;

public class FlinkSQL16_Function_UDF {

    public static void main(String[] args) throws Exception {

        //1.获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        //2.读取端口数据并转换为JavaBean
        SingleOutputStreamOperator<WaterSensor> waterSensorDS = env.socketTextStream("hadoop102", 9999)
                .map(line -> {
                    String[] fields = line.split(",");
                    return new WaterSensor(fields[0],
                            Long.parseLong(fields[1]),
                            Double.parseDouble(fields[2]));
                });

        //3.将流转换为动态表
        Table table = tableEnv.fromDataStream(waterSensorDS);

        //4.使用自定义的函数
        //4.1 TableAPI:不注册使用
        Table select1 = table
                .select($("id"),
                        call(ReplaceFunc.class, $("id")));

        //4.2 TableAPI:注册使用
        tableEnv.createTemporarySystemFunction("myReplace", ReplaceFunc.class);
        Table select2 = table
                .select($("id"),
                        call("myReplace", $("id")));

        //4.3 SQL:注册使用
        //tableEnv.createTemporarySystemFunction("myReplace", ReplaceFunc.class);
        Table select3 = tableEnv.sqlQuery("select id,myReplace(id) from " + table);

        //5.转换为流进行打印
        tableEnv.toAppendStream(select1, Row.class).print("TableAPI:不注册使用>>>>>>>>>");
        tableEnv.toAppendStream(select2, Row.class).print("TableAPI:注册使用>>>>>>>>>>>");
        tableEnv.toAppendStream(select3, Row.class).print("SQL:注册使用>>>>>>>>>>>>>>>>");

        //6.启动
        env.execute();
    }

    //将"_"转换为"-"
    public static class ReplaceFunc extends ScalarFunction {
        public String eval(String value) {
            return value.replace("_", "-");
        }
    }


}
